<template>
  <div class="card content-box">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item :label="t('common.field.config')" prop="config_id">
            <SelectV3 v-model="ruleForm.config_id" :url="groupList" />
          </el-form-item>

          <el-form-item :label="t('common.field.label')" prop="label">
            <el-input v-model="ruleForm.label" />
          </el-form-item>

          <el-form-item :label="t('common.field.field')" prop="field">
            <el-input v-model="ruleForm.field" />
          </el-form-item>

          <el-form-item :label="t('common.field.input')" prop="input">
            <el-radio-group v-model="ruleForm.input">
              <el-radio :label="'input'" border />
              <el-radio :label="'radio'" border />
              <el-radio :label="'select'" border />
              <el-radio :label="'switch'" border />
              <el-radio :label="'timePicker'" border />
              <el-radio :label="'timeSelect'" border />
              <el-radio :label="'datePicker'" border />
              <el-radio :label="'dateTimePicker'" border />
              <el-radio :label="'checkbox'" border />
              <el-radio :label="'resources'" border />
            </el-radio-group>
          </el-form-item>

          <el-form-item :label="t('common.field.value')" prop="value">
            <el-input v-model="ruleForm.value" />
          </el-form-item>
          
          <el-form-item :label="t('common.field.rules')" prop="rules">
            <el-col :span="1"> <el-button @click="addRules">+</el-button></el-col>
            <el-col :span="23" v-for="(rule, index) in ruleForm.rules" :key="index">
              <el-row :gutter="20">
                <el-col :span="4" v-for="(item, kIndex) in rule" :key="kIndex">
                  <el-input v-model="ruleForm.rules[index][kIndex]">
                    <template #prepend>{{ kIndex }}</template>
                  </el-input>
                </el-col>
                <el-button :icon="Delete" @click="delRules(index)" />
              </el-row>
            </el-col>
          </el-form-item>

          <el-form-item :label="t('common.field.props')" prop="props">
            <el-col :span="1"> <el-button @click="addProps">+</el-button></el-col>
            <el-col :span="5" v-for="(prop, index) in ruleForm.props" :key="index">
              <el-input v-for="(item, kIndex) in prop" :key="kIndex" v-model="ruleForm.props[index][kIndex]">
                <template #prepend>{{ kIndex }}</template>
                <template #append><el-button :icon="Delete" @click="delProps(index)" /></template>
              </el-input>
            </el-col>
          </el-form-item>

          <el-form-item :label="t('common.field.source')" prop="source">
            <el-col :span="1"> <el-button @click="addSource">+</el-button></el-col>
            <el-col :span="3" style="padding-left: 0" v-for="(_, index) in ruleForm.source" :key="index">
              <el-input v-model="ruleForm.source[index].label">
                <template #prepend>{{ t("common.field.label") }}</template>
                <template #append>
                  <el-button :icon="Delete" @click="delSource(index)" />
                </template>
              </el-input>
              <el-input v-model="ruleForm.source[index].value">
                <template #prepend>{{ t("common.field.value") }}</template>
                <template #append>
                  <el-button :icon="Delete" @click="delSource(index)" />
                </template>
              </el-input>
            </el-col>
          </el-form-item>

          <el-form-item :label="t('common.field.desc')" prop="desc">
            <el-input type="textarea" v-model="ruleForm.desc" maxlength="255" :autosize="{ minRows: 4, maxRows: 8 }" />
          </el-form-item>

          <el-form-item :label="t('common.status')" prop="status">
            <el-radio-group v-model="ruleForm.status">
              <el-radio :label="10" border>{{ $t("common.normal") }}</el-radio>
              <el-radio :label="20" border>{{ $t("common.disable") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8"></el-col>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </div>

  <el-dialog v-model="ruleDialogVisible" :title="t('common.field.ruleTitle')" width="40%" align-center>
    <el-form-item :label="t('common.field.ruleItem')" prop="ruleItem">
      <el-input v-model="ruleItem.rule" />
    </el-form-item>

    <el-form-item :label="t('common.field.ruleValue')" prop="value">
      <el-input v-model="ruleItem.value" />
    </el-form-item>

    <el-form-item :label="t('common.field.message')" prop="message">
      <el-input v-model="ruleItem.message" />
    </el-form-item>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="ruleDialogVisible = false" type="danger">{{ t("common.cancel") }}</el-button>
        <el-button @click="addRuleItem" type="success">{{ t("common.add") }}</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="propDialogVisible" :title="t('common.field.propTitle')" width="40%" align-center>
    <el-form-item :label="t('common.field.propItem')" prop="ruleItem">
      <el-input v-model="propItem.prop" />
    </el-form-item>

    <el-form-item :label="t('common.field.propValue')" prop="value">
      <el-input v-model="propItem.value" />
    </el-form-item>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="propDialogVisible = false" type="danger">{{ t("common.cancel") }}</el-button>
        <el-button @click="addPropItem" type="success">{{ t("common.add") }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts" name="dynamicForm">
import { reactive, ref, onBeforeMount } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { fieldCreate as Create, fieldUpdate as Update, fieldDetail as getDetail, groupList } from "@/api/modules/common";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { Delete } from "@element-plus/icons-vue";
import SelectV3 from "@/components/SelectV3/index.vue";

const route = useRoute();
const { t } = useI18n();

const ruleForm = reactive({
  id: route.params.id,
  config_id: route.params.config_id > 0 ? route.params.config_id : "",
  label: "",
  field: "",
  input: "input",
  value: "",
  source: [],
  props: [],
  rules: [
    {
      required: true,
      message: "必须"
    }
  ],
  desc: "",
  status: 10
});

onBeforeMount(() => {
  if (route.params.id > 0) {
    getDetail({ id: route.params.id }).then(response => {
      ruleForm.id = response.data.id;
      // ruleForm.config_id = response.data.config_id;
      // ruleForm.config_id = response.data.config_id;
      ruleForm.label = response.data.label;
      ruleForm.field = response.data.field;
      ruleForm.input = response.data.input;
      ruleForm.value = response.data.value;
      ruleForm.source = JSON.parse(response.data.source);
      ruleForm.rules = JSON.parse(response.data.rules);
      ruleForm.props = JSON.parse(response.data.props);
      ruleForm.desc = response.data.desc;
      ruleForm.status = response.data.status;
    });
  }
});

const tabStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  config_id: [{ required: true, message: t("common.field.rule.config"), trigger: "blur" }],
  label: [{ required: true, message: t("common.field.rule.label"), trigger: "blur" }],
  field: [{ required: true, message: t("common.field.rule.field"), trigger: "blur" }],
  input_type: [{ required: true, message: t("common.field.rule.input"), trigger: "blur" }]
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      const action = ruleForm.id > 0 ? Update : Create;
      const Form = JSON.parse(JSON.stringify(ruleForm));
      action(Form).then(response => {
        ElMessage.success(response.message);
        setTimeout(() => {
          if (route.meta.isAffix) return;
          tabStore.removeTabs(route.fullPath);
          keepAliveStore.removeKeepAliveName(route.name as string);
        }, 200);
      });
    } else {
      ElMessage.error("请根据提示输入信息！");
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const addSource = () => {
  ruleForm.source.push({
    value: "",
    label: ""
  });
};
const delSource = index => {
  ruleForm.source.splice(index, 1);
};

const propDialogVisible = ref(false);
const propItem = reactive({
  prop: "",
  value: ""
});

const addProps = () => {
  propDialogVisible.value = true;
};
const addPropItem = () => {
  if (!propItem.prop) {
    return ElMessage.error(t("common.field.rule.prop"));
  }
  if (!propItem.value) {
    return ElMessage.error(t("common.field.rule.value"));
  }

  const item = {};
  item[propItem.prop] = propItem.value;
  ruleForm.props.push(item);
  propItem.prop = "";
  propItem.value = "";
  propDialogVisible.value = false;
};

const delProps = index => {
  ruleForm.props.splice(index, 1);
};

const ruleDialogVisible = ref(false);
const ruleItem = reactive({
  rule: "",
  ruleValue: "",
  message: ""
});

const addRules = () => {
  ruleDialogVisible.value = true;
};

const addRuleItem = () => {
  if (!ruleItem.rule) {
    return ElMessage.error(t("common.field.rule.rule"));
  }
  if (!ruleItem.value) {
    return ElMessage.error(t("common.field.rule.value"));
  }
  if (!ruleItem.message) {
    return ElMessage.error(t("common.field.rule.message"));
  }

  const item = {};
  item[ruleItem.rule] = ruleItem.value;
  item.message = ruleItem.message;
  ruleForm.rules.push(item);
  ruleItem.rule = "";
  ruleItem.value = "";
  ruleItem.message = "";
  ruleDialogVisible.value = false;
};
const delRules = index => {
  ruleForm.rules.splice(index, 1);
};
</script>

<style scoped lang="scss">
@import "./edit.scss";
</style>
